package com.shen.demo.modules.backdoor.service;

import com.shen.demo.modules.backdoor.dao.BackDoorDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.StringJoiner;

/**
 * 后台接口业务层具体实现类
 *
 * @author syn
 */
@Slf4j
@Service
public class BackDoorService {
    @Value("${services.download.download-ip:83.3.250.189}")
    private String downloadIp;
    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private BackDoorDao backDoorDao;

    /**
     * 打印文件二进制编码
     *
     * @param filePath 文件路径
     * @return 打印二进制编码
     */
    public String printFileCode(String filePath) {
        byte[] sourceFileBytes;
        StringJoiner stringJoiner = new StringJoiner(",");
        try (FileInputStream sourceFileInputStream = new FileInputStream(filePath);
             ByteArrayOutputStream sourceOutputStream = new ByteArrayOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = sourceFileInputStream.read(buffer)) != -1) {
                sourceOutputStream.write(buffer, 0, len);
            }
            sourceFileBytes = sourceOutputStream.toByteArray();
            for (byte b : sourceFileBytes) {
                stringJoiner.add(String.valueOf(b));
            }
            log.info("[打印文件二进制编码] :[{}]", stringJoiner);
            log.info("[打印文件流] :[{}]", sourceOutputStream);
            log.info("[打印文件流的字节数组，以UTF-8编码形式展示] :[{}]", new String(sourceFileBytes, StandardCharsets.UTF_8));
            return new String(sourceFileBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.warn("[打印文件二进编码] 异常:", e);
        }
        return "";
    }

    /**
     * 插入文件的二进制字节数据
     *
     * @param filePath 文件路径
     * @return 插入结果
     */
    public String insertFileCode(String filePath) {
        byte[] sourceFileBytes;
        boolean isSuccess = false;
        try (FileInputStream sourceFileInputStream = new FileInputStream(filePath);
             ByteArrayOutputStream sourceOutputStream = new ByteArrayOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = sourceFileInputStream.read(buffer)) != -1) {
                sourceOutputStream.write(buffer, 0, len);
            }
            sourceFileBytes = sourceOutputStream.toByteArray();
            isSuccess = backDoorDao.insertFileCode(sourceFileBytes);
        } catch (Exception e) {
            log.warn("[插入二进制字节数据异常] 异常:", e);
        }
        if (isSuccess) {
            return "ok";
        }
        return "false";
    }

    /**
     * 生成文件
     *
     * @param fileContent 文件内容
     * @param fileDir     存储的文件夹路径
     * @param fileName    文件名
     * @return 文件的绝对路径
     */
    public String buildFile(String fileContent, String fileDir, String fileName) {
        String filePath = fileDir + fileName;
        try {
            //内容写入文件
            writeToFIle(filePath, fileContent);
            //文件内容读取
            log.info("文件内容为:{}", fileContent);
        } catch (Exception e) {
            log.warn("RandomAccessFile操作文件异常:", e);
            return "";
        }
        return "http://" + downloadIp + ":" + serverPort + "/backdoor/download?fileName=" + fileName;
    }

    /**
     * 内容写入文件
     *
     * @param filePath    文件路径
     * @param fileContent 文件内容
     * @throws IOException IO异常
     */
    private void writeToFIle(String filePath, String fileContent) throws IOException {
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw")) {
            //清空文件内容
            randomAccessFile.setLength(0);
            //写入新内容
            randomAccessFile.write(fileContent.getBytes(StandardCharsets.UTF_8));
        }
    }

}
